#include "AuthenticationCard.h"
#include "ui_AuthenticationCard.h"
#include "Tools/MyUrl.h"
#include "Tools/UiUpdateMediator.h"

#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QByteArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>

AuthenticationCard::AuthenticationCard(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::AuthenticationCard)
{
    ui->setupUi(this);
}

AuthenticationCard::AuthenticationCard(DeviceAuthentication *device_auth, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::AuthenticationCard)
{
    ui->setupUi(this);
    this->InitUi(device_auth);
}

void AuthenticationCard::InitUi(DeviceAuthentication* device_auth)
{
    this->device_auth = new DeviceAuthentication();
    this->device_auth->m_deviceId = device_auth->m_deviceId;
    this->device_auth->m_username = device_auth->m_username;
    this->device_auth->m_password = device_auth->m_password;

    this->ui->lineEdit_deviceId->setText(this->device_auth->m_deviceId);
    this->ui->lineEdit_username->setText(this->device_auth->m_username);
    this->ui->lineEdit_password->setText(this->device_auth->m_password);

    this->ui->lineEdit_deviceId->setToolTip(this->device_auth->m_deviceId);
    this->ui->lineEdit_username->setToolTip(this->device_auth->m_username);
    this->ui->lineEdit_password->setToolTip(this->device_auth->m_password);

    this->ui->lineEdit_deviceId->setReadOnly(true);
    this->ui->lineEdit_username->setReadOnly(true);
    this->ui->lineEdit_password->setReadOnly(true);

}

AuthenticationCard::~AuthenticationCard()
{
    delete ui;
}

void AuthenticationCard::on_pushButton_edit_clicked()
{
    if(this->ui->pushButton_edit->text() == "编辑")
    {
        this->ui->pushButton_edit->setText("保存");
        this->ui->lineEdit_deviceId->setReadOnly(false);
        this->ui->lineEdit_username->setReadOnly(false);
        this->ui->lineEdit_password->setReadOnly(false);
        this->ui->lineEdit_deviceId->setFocus();
    }
    else
    {
        this->ui->pushButton_edit->setText("编辑");
        this->ui->lineEdit_deviceId->setReadOnly(true);
        this->ui->lineEdit_username->setReadOnly(true);
        this->ui->lineEdit_password->setReadOnly(true);

        if(this->ui->lineEdit_deviceId->text() == this->device_auth->m_deviceId &&
           this->ui->lineEdit_username->text() == this->device_auth->m_username &&
           this->ui->lineEdit_password->text() == this->device_auth->m_password)
        {
            return;
        }

        QNetworkAccessManager* manager = new QNetworkAccessManager();
        connect(manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply* reply){
            qDebug() << "认证修改成功" + this->ui->lineEdit_deviceId->text() << __LINE__ << __FILE_NAME__;
            emit UiUpdateMediator::getInstance()->updateDevice();
            emit UiUpdateMediator::getInstance()->updateAuthentication();
        });

        QJsonObject jsonData;
        jsonData["device_id"] = this->device_auth->m_deviceId;
        jsonData["new_device_id"] = this->ui->lineEdit_deviceId->text();
        jsonData["new_username"] = this->ui->lineEdit_username->text();
        jsonData["new_password"] = this->ui->lineEdit_password->text();

        QJsonDocument doc(jsonData);
        QNetworkRequest* request = new QNetworkRequest(QUrl(MyUrl::authUpdate));
        request->setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
        manager->post(*request, doc.toJson(QJsonDocument::Compact));
    }

}


void AuthenticationCard::on_pushButton_delete_clicked()
{
    QMessageBox::StandardButton result = showDeleteConfirmBox(this, this->ui->lineEdit_deviceId->text());

    if(result == QMessageBox::Yes)
    {
        QNetworkAccessManager* manager = new QNetworkAccessManager();
        connect(manager, &QNetworkAccessManager::finished, this,[=](QNetworkReply* reply){
            int stateCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
            if(stateCode == 200)
            {
                qDebug() << "认证删除成功" + this->ui->lineEdit_deviceId->text() << __LINE__ << __FILE_NAME__;
                emit UiUpdateMediator::getInstance()->updateDevice();
                emit UiUpdateMediator::getInstance()->updateAuthentication();
            }
        });

        QJsonObject jsonData;
        jsonData["device_id"] = this->device_auth->m_deviceId;
        QJsonDocument doc(jsonData);

        QNetworkRequest* request = new QNetworkRequest(QUrl(MyUrl::authDelete));
        request->setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
        manager->post(*request, doc.toJson(QJsonDocument::Compact));
    }
}

QMessageBox::StandardButton AuthenticationCard::showDeleteConfirmBox(QWidget *parent, const QString &deviceId)
{
    QMessageBox msgBox(parent);
    msgBox.setWindowTitle("确认删除");
    QIcon icon("E:/ComplexProject/IOT_DM/IOT_DM_Client/IOT_DM/Resources/warning.svg");
    msgBox.setIconPixmap(icon.pixmap(48, 48));

    msgBox.setStyleSheet(R"(
    QMessageBox {
        background-color: #ffffff;
        color: #333333;
    }
    QMessageBox QLabel {
        color: #333333;
    }
    QMessageBox QPushButton {
        border-radius: 18px;
        min-width: 80px;
        height: 36px;
    }
)");
    QString content = QString("<span style='font-size:16px; font-weight:500; color:#333;'>确定要删除设备「%1」吗？</span><br/><br/>"
                              "<span style='font-size:14px; color:#666;'>删除后设备数据将无法恢复，请谨慎操作。</span>").arg(deviceId);
    msgBox.setText(content);
    msgBox.setTextFormat(Qt::RichText);

    QPushButton *cancelBtn = msgBox.addButton("取消", QMessageBox::NoRole);
    QPushButton *deleteBtn = msgBox.addButton("删除", QMessageBox::YesRole);

    QString btnStyle = R"(
        QPushButton {
            border-radius: 18px;
            min-width: 80px;
            height: 36px;
            font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
            font-size: 14px;
            border: none;
        }
        QPushButton[text="取消"] {
            background-color: #f5f5f5;
            color: #555;
        }
        QPushButton[text="取消"]:hover {
            background-color: #eeeeee;
        }
        QPushButton[text="删除"] {
            background-color: #f76c5e;
            color: white;
        }
        QPushButton[text="删除"]:hover {
            background-color: #f98274;
        }
    )";
    cancelBtn->setStyleSheet(btnStyle);
    deleteBtn->setStyleSheet(btnStyle);

    msgBox.setFixedSize(400, 200);
    QFont msgFont = msgBox.font();

    msgBox.setFont(msgFont);

    msgBox.exec();
    if (msgBox.clickedButton() == deleteBtn)
    {
        return QMessageBox::Yes;
    }
    else
    {
        return QMessageBox::No;
    }
}

